<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style>
    input[type='text'] {
      width: 200px;
      height: 20px;
    }
    .error {
      color: red;
    }
  </style>
  <body>
    <form action="https://8cf5-43-153-120-12.ngrok.io/pay/notify" method="post">
      <button>123</button>
    </form>
    <div>
      <h3>user</h3>
      <form id="login">
        用户名<input type="text" name="username" /> 密码<input
          type="password"
          name="password"
        /><button id="login_btn">登录</button>
      </form>
      <form id="form" style="margin-top: 20px">
        用户名 <input type="username" name="username" /> 密码
        <input type="password" name="password" /> 邮箱
        <input type="email" name="email" /> 手机号
        <input type="text" name="phone" />
        <span class="error"></span>
        <button id="register">注册用户</button>
      </form>
      <button id="profile">获取用户</button>
      <button id="logoutBtn">退出登录</button>
    </div>

    <div>
      <h3>propmpt</h3>
      <input type="file" name="file" id="uploadFile" />
      <form id="createBanner" style="margin-top: 20px">
        标题 <input type="text" name="text" /> 描述
        <input type="text" name="description" />
        详情<input type="text" name="detail" />
        <button>确认</button>
      </form>
      <button id="bannerList">获取列表</button>
      <button id="bannerDel">删除</button>
    </div>

    <div>
      <h3>分类</h3>
      <form id="createCategory" style="margin-top: 20px">
        名称 <input type="text" name="name" />
        <button>确认</button>
      </form>
      <button id="categoryList">获取列表</button>
      <button id="categoryDel">删除</button>
    </div>

    <div>
      <h3>商品</h3>
      <input type="file" name="file" id="uploadGoodFile" />
      <form id="goodForm" style="margin-top: 20px">
        名称 <input type="text" name="name" /> 价格
        <input type="text" name="price" /> 描述
        <input type="text" name="description" />
        <label>分类</label>
        <div name="category" id="categoryBox"></div>
        <label>之前价格</label>
        <input type="text" name="oldPrice" />
        <label>商品连接</label>
        <input type="text" name="link" />
        <label>关键词</label>
        <input
          type="checkbox"
          name="keywords"
          value="https://www.baidu.com [MCGRAW DRAGONFLY] is $329 (orig. $528)"
        />MCGRAW DRAGONFLY is $329 (orig. $528)
        <input
          type="checkbox"
          name="keywords"
          value="Theory offers an https://www.toryburch.com/en-us/sale/view-all/ [up to 60% off+extra 25% off Clothing Sale]"
        />Theory offers an up to 60% off+extra 25% off Clothing Sale
        <input type="checkbox" name="keywords" value="Free shipping." />Free
        shipping.
        <button>确认</button>
      </form>
      <button id="goodList">获取列表</button>
      <button id="goodRemove">删除</button>
    </div>

    <div>
      <h3>shoplist</h3>
      <div id="shopList"></div>
      <button id="uploadMutiple">批量上传</button>
    </div>
    <div>
      <h2>carts</h2>
      <form id="carts">
        商品<input type="text" name="good" /> 数量<input
          type="number"
          name="num"
        />
        是否选中 <input type="checkbox" name="is_select" />
        <button>提交</button>
      </form>
    </div>

    <div>
      <h2>carts list</h2>
      <div id="cart_list"></div>
      <div id="total_price"></div>
      <button id="pay">生成订单支付</button>
      <button id="no_pay">生成订单不支付</button>
    </div>
    <div>
      <h2>order list</h2>
      <div id="order_list"></div>
    </div>
    <script src="./shopList.js"></script>
    <script>
      const uploadFile = document.getElementById('uploadFile');
      let fileId = '';
      async function getCategory() {
        let res = await request('http://localhost:3000/category/list', {
          method: 'get',
        });
        categoryBox.innerHTML = res
          .map((item) => {
            return `<input type='checkbox' name='categories' value="${item.id}">${item.name}</input>`;
          })
          .join('');
      }
      getCategory();
      function generateBody(form) {
        const formData = new FormData(form);
        const values = {};
        for (let [key, value] of formData.entries()) {
          if (key === 'categories' || key === 'keywords') {
            if (!values[key]) {
              values[key] = [];
            }
            values[key].push(value);
          } else {
            values[key] = value;
          }
        }

        return values;
      }
      function handleUrl(params) {
        return new URLSearchParams(params).toString();
      }
      function request(url, options) {
        const defaultOptions = {
          method: 'get',
          headers: {
            'Content-Type': 'application/json',
            authorization: 'Bearer' + ' ' + localStorage.getItem('token'),
          },
        };
        const newHeaders = { ...defaultOptions.headers, ...options.headers };
        options = { ...defaultOptions, ...options };
        options.headers = newHeaders;
        let config = {};
        const { method, data, params, headers } = options;
        if (data && data !== undefined) {
          console.log(options.headers['Content-Type']);
          if (options.headers['Content-Type'] === 'multipart/form-data') {
            config.body = data;
            delete options.headers['Content-Type'];
          } else {
            config.body = JSON.stringify(data);
          }
          delete options.data;
        }
        if (params && data !== undefined && params.trim().length > 0) {
          url = url + '?' + handleUrl(params);
          delete options.params;
        }
        config = { ...config, ...options };
        return new Promise((resolve, reject) => {
          fetch(url, config)
            .then((res) => {
              if (res.headers.get('token')) {
                localStorage.setItem('token', res.headers.get('token'));
              }
              return res.json();
            })
            .then((res) => {
              resolve(res);
            })
            .catch((err) => {
              reject(err);
            });
        });
      }
      async function login(e) {
        e.preventDefault();
        const form = document.getElementById('login');
        const values = generateBody(form);
        let res = await request('http://localhost:3000/auth/login', {
          method: 'post',
          data: { ...values },
        });
        localStorage.setItem('token', res.access_token);
      }
      async function getProfile() {
        let res = await request('http://localhost:3000/user/profile', {
          headers: {
            'Content-Type': 'application/json',
          },
        });

        console.log(res);
      }
      async function registerUser(e) {
        e.preventDefault();
        const form = document.getElementById('form');
        const values = generateBody(form);
        let res = await request('http://localhost:3000/user/create', {
          method: 'post',
          data: {
            ...values,
          },
        });
        if (res.error) {
          document.querySelector('.error').innerHTML = res.message.join(',');
        } else {
          document.querySelector('.error').innerHTML = '';
        }
      }
      async function logout() {
        let res = await request('http://localhost:3000/auth/logout', {
          method: 'post',
        });
        if (res.code == 200) {
          localStorage.clear();
        }
        console.log(res);
      }
      async function createBannerHandler(e) {
        e.preventDefault();
        const form = document.getElementById('createBanner');
        if (fileId === '') {
          alert('请先上传图片');
          return;
        }
        const values = generateBody(form);
        values.media = fileId;
        let res = await request('http://localhost:3000/propmpt/create', {
          method: 'post',
          data: values,
        });
        console.log(res);
      }
      async function uploadFileHander(e) {
        const file = e.target.files[0];
        const formdata = new FormData();
        formdata.append('file', file);
        formdata.append('dir', 'propmpt');
        let res = await request('http://localhost:3000/media/upload', {
          method: 'post',
          headers: {
            'Content-Type': 'multipart/form-data',
          },
          data: formdata,
        });
        fileId = res.id;
      }
      async function bannerListHandler() {
        let res = await request('http://localhost:3000/propmpt/list', {
          method: 'get',
        });
        console.log(res);
      }

      async function bannerDelHandler() {
        let res = await request(
          'http://localhost:3000/banner/delete/a3a0d87f-890f-4b11-bd99-cd6e8a8f6b7d',
          {
            method: 'delete',
          },
        );
        console.log(res);
      }
      async function createCategoryHandler(e) {
        e.preventDefault();
        const form = document.getElementById('createCategory');
        const values = generateBody(form);
        let res = await request('http://localhost:3000/category/create', {
          method: 'post',
          data: values,
        });
        console.log(res);
      }
      async function categoryListHandler() {
        let res = await request('http://localhost:3000/category/list', {
          method: 'get',
        });
        console.log(res);
      }
      async function categoryDelHandler() {
        let res = await request('http://localhost:3000/category/delete/1', {
          method: 'delete',
        });
        console.log(res);
      }

      async function goodListHandler() {
        let res = await request('http://localhost:3000/good/list', {
          method: 'get',
        });
        console.log(res);
      }
      function generateFileObjByPath(path) {
        return new Promise((resolve, reject) => {
          const xhr = new XMLHttpRequest();
          xhr.open('GET', `./download/${path}`, true);
          xhr.responseType = 'blob';
          xhr.onload = function () {
            if (this.status === 200) {
              const file = new File([this.response], path, {
                type: 'text/plain',
              });
              resolve(file);
            }
          };
          xhr.send();
        });
      }
      function uploadFile2(file, dir) {
        return new Promise(async (resolve, reject) => {
          setTimeout(async () => {
            const formdata = new FormData();
            formdata.append('file', file);
            formdata.append('dir', dir);
            setTimeout(async () => {
              let res = await request('http://localhost:3000/media/upload', {
                method: 'post',
                headers: {
                  'Content-Type': 'multipart/form-data',
                },
                data: formdata,
              });
              resolve(res.id);
            }, 2000);
          });
        });
      }
      uploadFile.onchange = uploadFileHander;
      uploadGoodFile.onchange = uploadFileHander;
      login_btn.onclick = login;
      profile.onclick = getProfile;
      logoutBtn.onclick = logout;
      form.onsubmit = registerUser;
      login.onsubmit = login;
      createBanner.onsubmit = createBannerHandler;
      bannerList.onclick = bannerListHandler;
      bannerDel.onclick = bannerDelHandler;
      createCategory.onsubmit = createCategoryHandler;
      categoryList.onclick = categoryListHandler;
      categoryDel.onclick = categoryDelHandler;
      goodList.onclick = goodListHandler;
      carts.onsubmit = async function (e) {
        e.preventDefault();
        const form = document.getElementById('carts');
        const values = generateBody(form);
        values.is_select = values.is_select === 'on' ? 1 : 0;
        console.log(values);

        let res = await request('http://localhost:3000/carts/create', {
          method: 'post',
          data: values,
        });
      };
      function getCartsList() {
        request('http://localhost:3000/carts/list', {
          method: 'get',
        }).then((res) => {
          count_price = res.reduce((prev, cur) => {
            if (cur.is_select) {
              return (
                prev +
                cur.num * (cur.good.price || cur.good.priceoldPrice).toFixed(2)
              );
            }
            return prev;
          }, 0);
          total_price.innerHTML = count_price;
          total_price.style.color = 'black';
          let html = res
            .map((item) => {
              return `<div>
              <span>${item.good.description}</span>
              <span style="color: red;">${item.num}</span>
              <span style="color: blue;">${item.is_select}</span>
            </div>`;
            })
            .join('');
          document.getElementById('cart_list').innerHTML = html;
        });
      }
      function getOrderList() {
        request('http://localhost:3000/order/list', {
          method: 'get',
        }).then((res) => {
          let html = res
            .map((item) => {
              if (item.expire_time) {
                return `<div>
              <span>${item.total_price}</span>
              <span style="color: red;">${item.status}</span>
              <span class='expire_time' expire_time=${item.expire_time} style="color: red;"></span>
            </div>`;
              } else {
                return `<div>
              <span>${item.total_price}</span>
              <span style="color: red;">${item.status}</span>
            </div>`;
              }
            })
            .join('');
          document.getElementById('order_list').innerHTML = html;
          let expire_time = document.querySelectorAll('.expire_time');
          expire_time.forEach((item) => {
            countdown(
              new Date(item.getAttribute('expire_time')).getTime(),
              item,
            );
          });
        });
      }
      function countdown(expirationDate, dom) {
        // 获取当前时间
        const now = new Date().getTime();
        // 计算剩余时间（毫秒）
        const remainingTime = expirationDate - now;
        // 如果剩余时间小于等于0，则倒计时结束
        if (remainingTime <= 0) {
          console.log('倒计时结束');
          return;
        }
        // 将剩余时间转换为秒数
        const remainingSeconds = Math.floor(remainingTime / 1000);
        // 分别计算剩余的小时、分钟和秒数
        const hours = Math.floor(remainingSeconds / 3600);
        const minutes = Math.floor((remainingSeconds % 3600) / 60);
        const seconds = remainingSeconds % 60;
        // 输出倒计时结果
        console.log(`${hours}:${minutes}:${seconds}`);
        dom.innerHTML = `${hours}:${minutes}:${seconds}`;
        // 每隔1秒更新倒计时
        setTimeout(() => {
          countdown(expirationDate, dom);
        }, 1000);
      }
      getOrderList();
      getCartsList();
      uploadMutiple.onclick = async function () {
        for (let index = 0; index < shoplist.length; index++) {
          const shop = shoplist[index];
          const form = document.createElement('form');
          const input = document.createElement('input');
          const fileArr = [
            generateFileObjByPath(`${index + 1}-shop.png`),
            generateFileObjByPath(`${index + 1}-icon.png`),
          ];
          let res = await Promise.all(fileArr);
          const curFileId = await uploadFile2(res[0], 'goods');
          const curFileIconId = await uploadFile2(res[1], 'icons');
          if (!curFileId) {
            alert('请先上传图片');
            return;
          }
          if (!curFileIconId) {
            alert('请先上传图片');
            return;
          }
          const values = {};
          values.name = shop.title;
          values.price = shop.price;
          values.description = shop.desc;
          values.oldPrice = shop.oldPrice;
          values.keywords = shop.keywords.join().split(',');
          values.categories = '1';
          values.media = curFileId;
          values.mediaIcon = curFileIconId;
          let res2 = await request('http://localhost:3000/good/create', {
            method: 'post',
            data: values,
          });
          console.log(res2);
        }
      };
      pay.onclick = async function () {
        const res = await request('http://localhost:3000/order/create', {
          method: 'post',
          data: {
            status: 2,
            total_price: count_price,
          },
        });
        console.log(res);
      };
      no_pay.onclick = async function () {
        const res = await request('http://localhost:3000/order/create', {
          method: 'post',
          data: {
            status: 1,
            total_price: count_price,
          },
        });
        console.log(res);
      };
      goodForm.onsubmit = async function (e) {
        e.preventDefault();
        const form = document.getElementById('goodForm');
        const values = generateBody(form);
        values.media = fileId;
        let res = await request('http://localhost:3000/good/create', {
          method: 'post',
          data: values,
        });
        console.log(res);
      };

      window.addEventListener('beforeunload', function (event) {
        event.preventDefault();
        event.returnValue = '';
        return ''; // 兼容旧版本浏览器
      });
    </script>
  </body>
</html>
